import { Component, OnInit, EventEmitter } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { FormsModule, Validators, FormGroup, FormControl } from '@angular/forms';
import { DataService } from '../../../services/data.service';
import { EditService } from './edit.service';
import * as moment from 'moment';
import * as _ from 'lodash';
import { FileUploader } from "ng2-file-upload";
import { environment } from '../../../../environments/environment';
import { AppPaginationComponent, PaginationModel } from "../../../widgets/pagination/pagination.component";
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import { Util } from 'app/common/util';

@Component({
  selector: 'product-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss'],
  providers: [EditService]
})
export class ProductEditComponent implements OnInit {
  // lodash
  public _: any = _;
  // index
  public index: any;
  // 路由operate
  public operate: any;
  // 销售渠道字典值
  public saleslList = [];
  // 销售渠道多选下拉框
  public salesSelectList = [];
  // 获取权限按钮
  public menuResourceSet = sessionStorage.getItem('btn-otm');
  // 字典值
  public dictionaryList: any = {};
  // 产品方案数据  YDD=一对多
  public cpfaYDDDataList = [];
  // 法律文件数据
  public flwjYDDDataList = [];
  // 备案数据
  public baYDDDataList = [];
  // 上传文件名
  public fileName;
  // 补充协议数据
  public bcxyYDDDataList = [];
  // 账户信息数据
  public zhxxYDDDataList = [];
  // 投资信息数据
  public tzxxYDDDataList = [];
  // 清算信息数据
  public qsxxYDDDataList = [];
  // 其他数据
  public qtYDDDataList = [];
  // 产品方案
  public cpfaYDD: any;
  // 法律文件
  public flwjYDD: any;
  //  托管人数据
  // public bankDictionaryList = [];
  // 备案
  public baYDD: any;
  // 补充协议
  public bcxyYDD: any;
  // 账户信息
  public zhxxYDD: any;
  // 投资信息
  public tzxxYDD: any;
  // 清算信息
  public qsxxYDD: any;
  // 其他
  public qtYDD: any;
  // 用于保存显示的附件列表
  public activeFileList = [];
  // 用于保存激活的文件tab大类
  public activeFileType = "";
  // 初始化定义uploader变量,用来配置input中的uploader属性
  public uploader: FileUploader = new FileUploader({});
  // 上传文件的名称
  public uploadFileName: any = "";
  // 产品上传参数
  public sCreatorNo: any;
  public sCreator: any;
  public sAttachCode: any;
  public nFundNo: any;
  public nAttachNo: any;
  public sAttachType: any;
  public parentCode: any;
  public parentType: any;
  public sFundType: any;
  // 选择文件状态
  public fileStatus = false;
  // 附件历史数据
  public fileHistoryData: any;
  // 投资经理信息
  public otmManagerList: any;
  // 投资经理分页
  public otmManagerBody = {
    nFundNo: '',
    pageIndex: 1,
    pageSize: 10,
  };
  //一对多分页配置
  public otmManagerListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  // 一对多基础信息
  public otmAddOrEditBody: any = {
    sFundCategory: "",
    sCapitalproType: "",
    sValuationMethod: "",
    sBank: "",
    sSalesChannel: "",
    sStopType: "",
    sWhichTa: "",
    sCurrency: "",
    nValueDec: "",
    sWsFundAttribute: "",
    sWsFundProperty: "",
    sIsAisle: "0",
    sIsContractPeriod: "1",

  };
  // 一对一基础信息
  public otoAddOrEditBody: any = {
    sFundCategory: "",
    sIsAisle: "0",
    sPrincipalType: "0",
    sValuationTable: "",
    sCapitalproType: "",
    nContractPeriod: "",
    sValuationMethod: "",
    sBank: "",
    sStopType: "",
    nValueDec: "",
    sIsContractPeriod: "1"
  };
  //公募基础信息绑定数据
  public baseInfoPost: any = {
    sFundCode: '',
    sFundName: '',
    sFullName: '',
    sFundType: '0',
    sFundCategory: '',
    sIsQdii: '0',
    sInvestStyle: '',
    sPmAccount: '',
    sPmName: '',
    sListType: '0',
    sExchange: '',
    sBank: '',
    dBankConfirm: '',
    sInvestScope: '',
    sBenchmark: '',
    sManagementFee: '',
    sTrusteeFee: '',
    sOtherFee: '',
    dIssue: '',
    dEstablishment: '',
    sCreator: '',
    sCreatorNo: '',
    sIsRegisterChg: '',
    nRegisterChgNo: '',
    sStatus: '',
    sStatusRunning: '',
    sSubStatus: "",
    sSubStatusSet: "",
    sRemark: '',
    dUpdateTime: '',
    dCreateTime: '',
    sOtherCode1: "",
    sOtherCode2: "",
    sOtherCode3: ""
  };
  public list = [];
  public type = "a";
  public step = 2;
  // 获取产品是否为已停止状态
  public isStop: any;

  constructor(
    private route: ActivatedRoute,
    public dataService: DataService,
    public editService: EditService,
    public router: Router
  ) {
    let that = this;
    // 路由切换
    this.route.params.subscribe((data) => {
      this.nFundNo = data.nFundNo;
      this.operate = data.operate;
      this.index = data.index;
      // 编辑基础信息
      if (this.operate == "publicoffering") {

        that.pcGetSingleProduct();
      }else if(this.operate == "onetoone"){
        that.otoGetSingleProduct()
      }else if(this.operate == "onetomany"){
        that.otmGetSingleProduct()
        that.otmGetManager();
      }
      // 产品基础信息

      // 判断是否为已停止状态
      if (sessionStorage.getItem('otm_isStop') == 'isStop') {
        this.isStop = 'isStop';
      }
    })
  }

  ngOnInit() {
    // 初始化日期控件
    flatpickr.localize(zh);
    // 多选下拉框
    window['$'](".select2").select2();
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    // 销售渠道字典值
    this.saleslList = JSON.parse(localStorage.getItem("dictionaryList")).SALES_CHANNEL;
    // 托管行
    if (this.operate == "add") {
      window['$']('#nContractPeriod').attr("disabled", "disabled");
    }
    // 获取托管人数据
    // this.bankDictionaryList = JSON.parse(localStorage.getItem("bankDictionaryList"));
  }

  ngAfterViewInit() {
    this.ctrlDisabled();

  }

  // 加载附件树
  loadFileTree() {
    var that = this;
    let getBody = {
      "sFundType": 2,
      "nFundNo": this.nFundNo
    }
    this.editService.getFileTree(getBody).subscribe((data) => {
      if (data) {
        // 赋值前清空数据
        that.cpfaYDDDataList = [];
        that.flwjYDDDataList = [];
        that.baYDDDataList = [];
        that.bcxyYDDDataList = [];
        that.zhxxYDDDataList = [];
        that.tzxxYDDDataList = [];
        that.qsxxYDDDataList = [];
        that.qtYDDDataList = [];
        _.forEach(data.subTree, function (item, index) {
          // 保存附件列表展示的tab
          that.activeFileList.push(item.sAttachCode);
          switch (item.sAttachCode) {
            case "cpfaYDD":
              that.cpfaYDD = item.subTree;
              let _cpfaYDDDataList = [];
              _.forEach(that.cpfaYDD, function (ite) {          // ite是附件小分类
                _.forEach(ite.fileList, function (it) {         // it是附件
                  it.sFundType = ite.sFundType;                 // 附件类型 2
                  it["sParentType"] = item.sAttachType;         // 附件大分类名称 产品方案
                  it["sParentCode"] = ite.sParentCode;          // 附件大分类编码 cpfaYDD
                  it["parentType"] = ite.sAttachType;           // 附件小分类名称 产品需求表
                  it["attachCode"] = ite.sAttachCode;           // 附件小分类编码 cpxqbYDD
                  it["subNodeL"] = ite.fileList.length;         // 附件小分类长度
                  it["sType"] = "";                             // 附件小分类名称
                  it["editStatus"] = "0";                       // 附件名编辑状态
                  it["fileName"] =                           // 附件修改名称
                    it["fileType"] = that.Intercept(it.sAttachName);                          // 附件后缀
                  _cpfaYDDDataList.push(it);
                })
                ite.fileList[0]["sType"] = ite.sAttachType;     // 附件小分类名称
              });
              that.cpfaYDDDataList = _cpfaYDDDataList;
              break;
            case "flwjYDD":
              that.flwjYDD = item.subTree;
              let _flwjYDDDataList = [];
              _.forEach(that.flwjYDD, function (ite) {
                _.forEach(ite.fileList, function (it) {
                  it.sFundType = ite.sFundType;
                  it["sParentType"] = item.sAttachType;
                  it["sParentCode"] = ite.sParentCode;
                  it["parentType"] = ite.sAttachType;
                  it["attachCode"] = ite.sAttachCode;
                  it["subNodeL"] = ite.fileList.length;
                  it["sType"] = "";
                  it["editStatus"] = "0";
                  it["fileName"] = "";
                  it["fileType"] = that.Intercept(it.sAttachName);
                  _flwjYDDDataList.push(it);
                })
                ite.fileList[0]["sType"] = ite.sAttachType;
              });
              that.flwjYDDDataList = _flwjYDDDataList;
              break;
            case "baYDD":
              that.baYDD = item.subTree;
              let _baYDDDataList = [];
              _.forEach(that.baYDD, function (ite) {
                _.forEach(ite.fileList, function (it) {
                  it.sFundType = ite.sFundType;
                  it["sParentType"] = item.sAttachType;
                  it["sParentCode"] = ite.sParentCode;
                  it["parentType"] = ite.sAttachType;
                  it["attachCode"] = ite.sAttachCode;
                  it["subNodeL"] = ite.fileList.length;
                  it["sType"] = "";
                  it["editStatus"] = "0";
                  it["fileName"] = "";
                  it["fileType"] = that.Intercept(it.sAttachName);
                  _baYDDDataList.push(it);
                })
                ite.fileList[0]["sType"] = ite.sAttachType;
              });
              that.baYDDDataList = _baYDDDataList;
              break;
            case "bcxyYDD":
              that.bcxyYDD = item.subTree;
              let _bcxyYDDDataList = [];
              _.forEach(that.bcxyYDD, function (ite) {
                _.forEach(ite.fileList, function (it) {
                  it.sFundType = ite.sFundType;
                  it["sParentType"] = item.sAttachType;
                  it["sParentCode"] = ite.sParentCode;
                  it["parentType"] = ite.sAttachType;
                  it["attachCode"] = ite.sAttachCode;
                  it["subNodeL"] = ite.fileList.length;
                  it["sType"] = "";
                  it["editStatus"] = "0";
                  it["fileName"] = "";
                  it["fileType"] = that.Intercept(it.sAttachName);
                  _bcxyYDDDataList.push(it);
                })
                ite.fileList[0]["sType"] = ite.sAttachType;
              });
              that.bcxyYDDDataList = _bcxyYDDDataList;
              break;
            case "zhxxYDD":
              that.zhxxYDD = item.subTree;
              let _zhxxYDDDataList = [];
              _.forEach(that.zhxxYDD, function (ite) {
                _.forEach(ite.fileList, function (it) {
                  it.sFundType = ite.sFundType;
                  it["sParentType"] = item.sAttachType;
                  it["sParentCode"] = ite.sParentCode;
                  it["parentType"] = ite.sAttachType;
                  it["attachCode"] = ite.sAttachCode;
                  it["subNodeL"] = ite.fileList.length;
                  it["sType"] = "";
                  it["editStatus"] = "0";
                  it["fileName"] = "";
                  it["fileType"] = that.Intercept(it.sAttachName);
                  _zhxxYDDDataList.push(it);
                })
                ite.fileList[0]["sType"] = ite.sAttachType;
              });
              that.zhxxYDDDataList = _zhxxYDDDataList;
              break;
            case "tzxxYDD":
              that.tzxxYDD = item.subTree;
              let _tzxxYDDDataList = [];
              _.forEach(that.tzxxYDD, function (ite) {
                _.forEach(ite.fileList, function (it) {
                  it.sFundType = ite.sFundType;
                  it["sParentType"] = item.sAttachType;
                  it["sParentCode"] = ite.sParentCode;
                  it["parentType"] = ite.sAttachType;
                  it["attachCode"] = ite.sAttachCode;
                  it["subNodeL"] = ite.fileList.length;
                  it["sType"] = "";
                  it["editStatus"] = "0";
                  it["fileName"] = "";
                  it["fileType"] = that.Intercept(it.sAttachName);
                  _tzxxYDDDataList.push(it);
                })
                ite.fileList[0]["sType"] = ite.sAttachType;
              });
              that.tzxxYDDDataList = _tzxxYDDDataList;
              break;
            case "qsxxYDD":
              that.qsxxYDD = item.subTree;
              let _qsxxYDDDataList = [];
              _.forEach(that.qsxxYDD, function (ite) {
                _.forEach(ite.fileList, function (it) {
                  it.sFundType = ite.sFundType;
                  it["sParentType"] = item.sAttachType;
                  it["sParentCode"] = ite.sParentCode;
                  it["parentType"] = ite.sAttachType;
                  it["attachCode"] = ite.sAttachCode;
                  it["subNodeL"] = ite.fileList.length;
                  it["sType"] = "";
                  it["editStatus"] = "0";
                  it["fileName"] = "";
                  it["fileType"] = that.Intercept(it.sAttachName);
                  _qsxxYDDDataList.push(it);
                })
                ite.fileList[0]["sType"] = ite.sAttachType;
              });
              that.qsxxYDDDataList = _qsxxYDDDataList;
              break;
            case "qtYDD":
              that.qtYDD = item.subTree;
              let _qtYDDDataList = [];
              _.forEach(that.qtYDD, function (ite) {
                _.forEach(ite.fileList, function (it) {
                  it.sFundType = ite.sFundType;
                  it["sParentType"] = item.sAttachType;
                  it["sParentCode"] = ite.sParentCode;
                  it["parentType"] = ite.sAttachType;
                  it["attachCode"] = ite.sAttachCode;
                  it["subNodeL"] = ite.fileList.length;
                  it["sType"] = "";
                  it["editStatus"] = "0";
                  it["fileName"] = "";
                  it["fileType"] = that.Intercept(it.sAttachName);
                  _qtYDDDataList.push(it);
                })
                ite.fileList[0]["sType"] = ite.sAttachType;
              });
              that.qtYDDDataList = _qtYDDDataList;
              break;
          }
        })
        setTimeout(() => {
          that.activeFileTab();
        }, 500)
      }
    })
  }
  // 产品树文件分类新增对象
  addSubTreeItem(item, type) {
    let that = this;
    let index;
    this.activeFileType = item.sParentCode;
    let newItem: any = {
      sType: item.sType,              // 小分类名称
      subNodeL: item.subNodeL + 1,    // 长度+1
      attachCode: item.attachCode,    // 小分类编码
      parentType: item.parentType,    // 小分类名称
      sParentType: item.sParentType,  // 大分类名称
      sParentCode: item.sParentCode,  // 大分类编码
      sAttachParentType: "",
      nAttachNo: "",
      nFundNo: "",
      sAttachType: item.parentType,   // 小分类名称
      sAttachCode: item.attachCode,   // 小分类编码
      sLinkFundnos: null,
      sAttachName: null,
      sLinkPrincipalNo: null,
      sLinkPrincipal: null,
      sStatus: null,
      dCreateTime: null,
      sCreator: null,
      sCreatorNo: null,
      nVersion: null,
      sAttachParentCode: null,
      sPath: null,
      nLastAttachNo: null,
      sFundType: item.sFundType,
      editStatus: "0",
      fileName: "",
      fileType: ""
    }
    switch (type) {
      case "cpfaYDD":
        index = _.indexOf(this.cpfaYDDDataList, item);
        this.cpfaYDDDataList[index].sType = "";
        this.cpfaYDDDataList.splice(index, 0, newItem);
        break;
      case "flwjYDD":
        index = _.indexOf(this.flwjYDDDataList, item);
        this.flwjYDDDataList[index].sType = "";
        this.flwjYDDDataList.splice(index, 0, newItem);
        break;
      case "baYDD":
        index = _.indexOf(this.baYDDDataList, item);
        this.baYDDDataList[index].sType = "";
        this.baYDDDataList.splice(index, 0, newItem);
        break;
      case "bcxyYDD":
        index = _.indexOf(this.bcxyYDDDataList, item);
        this.bcxyYDDDataList[index].sType = "";
        this.bcxyYDDDataList.splice(index, 0, newItem);
        break;
      case "zhxxYDD":
        index = _.indexOf(this.zhxxYDDDataList, item);
        this.zhxxYDDDataList[index].sType = "";
        this.zhxxYDDDataList.splice(index, 0, newItem);
        break;
      case "tzxxYDD":
        index = _.indexOf(this.tzxxYDDDataList, item);
        this.tzxxYDDDataList[index].sType = "";
        this.tzxxYDDDataList.splice(index, 0, newItem);
        break;
      case "qsxxYDD":
        index = _.indexOf(this.qsxxYDDDataList, item);
        this.qsxxYDDDataList[index].sType = "";
        this.qsxxYDDDataList.splice(index, 0, newItem);
        break;
      case "qtYDD":
        index = _.indexOf(this.qtYDDDataList, item);
        this.qtYDDDataList[index].sType = "";
        this.qtYDDDataList.splice(index, 0, newItem);
        break;
    }
  }
  //  获取上传文件的文件名
  getFileName(value) {
    // let pos=value.lastIndexOf("\\");
    // this.fileName=value.substring(pos+1);
    // 兼容ie title不出现问题
    this.fileName = value;
  }
  // 显示上传文件框
  showUploadModal(item) {
    this.activeFileType = item.sParentCode;
    // 上传文件必填字段
    this.sAttachCode = item.attachCode;
    this.sAttachType = item.parentType;
    this.parentCode = item.sParentCode;
    this.parentType = item.sParentType;
    this.sFundType = item.sFundType;
    this.sFundType = item.sFundType;
    this.sCreator = sessionStorage.getItem('username');
    this.sCreatorNo = sessionStorage.getItem('username');

    if (item.nAttachNo == null) {
      this.nAttachNo = "";
    } else {
      this.nAttachNo = item.nAttachNo;
    }
    window['$']('#uploadModel').modal('show');
  }
  // 获取上传文件的名称
  selectedFileOnChanged(event: any) {
    this.uploadFileName = event.target.value;
    this.fileStatus = true;
  }
  // 上传文件
  uploadFile() {
    let that = this;
    let fileItem = _.last(this.uploader.queue);
    fileItem.url = environment.server + '/pms/v1/common/fundFile/file' + '?token=' + sessionStorage.getItem('token');
    fileItem.method = "POST";
    // 关联input框的“name”属性
    fileItem.alias = "file";
    fileItem.formData = [
      { key: "fileName", value: _.last(this.uploader.queue).file.name },
      { key: "nFundNo", value: this.nFundNo },
      { key: "nAttachNo", value: this.nAttachNo },
      { key: "sAttachCode", value: this.sAttachCode },
      { key: "sAttachType", value: this.sAttachType },
      { key: "parentCode", value: this.parentCode },
      { key: "parentType", value: this.parentType },
      { key: "sFundType", value: this.sFundType },
      { key: "sCreator", value: this.sCreator },
      { key: "sCreatorNo", value: this.sCreatorNo }
    ],
      // 添加 POST 其他参数
      this.uploader.onBuildItemForm = (item, form) => {
        _.forEach(fileItem.formData, item => {
          form.append(item.key, item.value);
        });
      };
    console.log("------文件上传参数----" + JSON.stringify(fileItem.formData));
    window['swal']({
      title: "提示",
      text: "是否确定上传 " + _.last(this.uploader.queue).file.name + " 附件?",
      type: "warning",
      showCancelButton: true,
      closeOnConfirm: false,
      confirmButtonText: "确认",
      confirmButtonColor: "#DD6B55",
      cancelButtonText: "取消",
      showLoaderOnConfirm: true,
    }, function (isConfirm) {
      if (isConfirm) {
        // 开始上传
        fileItem.upload();
        // 上传一个文件成功的回调
        fileItem.onSuccess = function (response, status, headers) {
          let resVal = JSON.parse(response);
          console.info(resVal);
          if (resVal.msg == "成功") {
            window["swal"]("成功", "文件上传成功!", "success");
            window['$']('#uploadModel').modal('hide');
            that.clearFileQueue();
            that.loadFileTree();
          } else {
            window["swal"](resVal.msg, resVal.detailMsg, "error");
            window['$']('#uploadModel').modal('hide');
            that.clearFileQueue();
          }
        }
      }
    })
  }
  // 清除FileUploader上传队列中的所有文件
  clearFileQueue() {
    this.uploader.clearQueue();
    this.fileStatus = false;
    window['$']('#fileInput').val("");
  }

  // 下载附件
  downLoadFile(item) {
    if (item.nAttachNo) {
      Util.attachDownload([item.nAttachNo]);
    } else {
      window['swal']("提示", "暂无文件下载", "warning");
    }
  }

  // 查看历史文件
  showHistoryVersion(item) {
    let that = this;
    this.activeFileType = item.sParentCode;
    this.editService.getFileHistory(item.nAttachNo).subscribe(data => {
      if (data) {
        that.fileHistoryData = data;
        // 附件后缀
        _.forEach(that.fileHistoryData, function (item) {
          item["fileType"] = that.Intercept(item.sAttachName);
        })
        window['$']("#detail-his-list-modal").modal('show');
      } else {
        window['swal']("提示", "暂无文件", "warning");
      }
    })
  }

  // 删除文件
  delFile(item) {
    let that = this;
    window["swal"]({
      title: "注意",
      text: "是否确定删除 " + item.sAttachName + " 附件？",
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      showCancelButton: true,
      closeOnConfirm: false,
      closeOnCancel: true,
      showLoaderOnConfirm: true
    }, function (isConfirm) {
      if (isConfirm) {
        that.editService.delFile(item.nAttachNo).subscribe(data => {
          if (data) {
            window['swal']("成功", "文件已删除！", "success");
            window['$']("#detail-his-list-modal").modal('hide');
            that.loadFileTree();
          } else {
            window['swal']("失败", data.msg, "error");
          }
        })
      }
    })
  }
  // 编辑附件名称
  editFileName(item, type) {
    let that = this;
    this.activeFileType = item.sParentCode;
    // 附件名长度
    let len = item.sAttachName.length;
    // 最后一个.的位置
    let lastDotIndex = item.sAttachName.lastIndexOf(".");
    let index;
    switch (type) {
      case "cpfaYDD":
        index = _.indexOf(this.cpfaYDDDataList, item);
        this.cpfaYDDDataList[index].fileName = item.sAttachName.substring(0, lastDotIndex);
        this.cpfaYDDDataList[index].fileType = item.sAttachName.substring(lastDotIndex, len + 1);
        this.cpfaYDDDataList[index].editStatus = "1";
        break;
      case "flwjYDD":
        index = _.indexOf(this.flwjYDDDataList, item);
        this.flwjYDDDataList[index].fileName = item.sAttachName.substring(0, lastDotIndex);
        this.flwjYDDDataList[index].fileType = item.sAttachName.substring(lastDotIndex, len + 1);
        this.flwjYDDDataList[index].editStatus = "1";
        break;
      case "baYDD":
        index = _.indexOf(this.baYDDDataList, item);
        this.baYDDDataList[index].fileName = item.sAttachName.substring(0, lastDotIndex);
        this.baYDDDataList[index].fileType = item.sAttachName.substring(lastDotIndex, len + 1);
        this.baYDDDataList[index].editStatus = "1";
        break
      case "bcxyYDD":
        index = _.indexOf(this.bcxyYDDDataList, item);
        this.bcxyYDDDataList[index].fileName = item.sAttachName.substring(0, lastDotIndex);
        this.bcxyYDDDataList[index].fileType = item.sAttachName.substring(lastDotIndex, len + 1);
        this.bcxyYDDDataList[index].editStatus = "1";
        break;
      case "zhxxYDD":
        index = _.indexOf(this.zhxxYDDDataList, item);
        this.zhxxYDDDataList[index].fileName = item.sAttachName.substring(0, lastDotIndex);
        this.zhxxYDDDataList[index].fileType = item.sAttachName.substring(lastDotIndex, len + 1);
        this.zhxxYDDDataList[index].editStatus = "1";
        break;
      case "tzxxYDD":
        index = _.indexOf(this.tzxxYDDDataList, item);
        this.tzxxYDDDataList[index].fileName = item.sAttachName.substring(0, lastDotIndex);
        this.tzxxYDDDataList[index].fileType = item.sAttachName.substring(lastDotIndex, len + 1);
        this.tzxxYDDDataList[index].editStatus = "1";
        break;
      case "qsxxYDD":
        index = _.indexOf(this.qsxxYDDDataList, item);
        this.qsxxYDDDataList[index].fileName = item.sAttachName.substring(0, lastDotIndex);
        this.qsxxYDDDataList[index].fileType = item.sAttachName.substring(lastDotIndex, len + 1);
        this.qsxxYDDDataList[index].editStatus = "1";
        break;
      case "qtYDD":
        index = _.indexOf(this.qtYDDDataList, item);
        this.qtYDDDataList[index].fileName = item.sAttachName.substring(0, lastDotIndex);
        this.qtYDDDataList[index].fileType = item.sAttachName.substring(lastDotIndex, len + 1);
        this.qtYDDDataList[index].editStatus = "1";
        break;
    }
  }
  // 修改附件名
  changeFileName(item) {
    let that = this;
    // 去掉附件名首尾空格
    let filename = _.trim(item.fileName);
    if (filename !== "" && filename !== null) {
      let newFileName = encodeURI(filename) + item.fileType;
      window['swal']({
        title: "提示",
        text: "附件名称是否确定修改为 " + filename + " ?",
        type: "warning",
        showCancelButton: true,
        closeOnConfirm: false,
        confirmButtonText: "确认",
        confirmButtonColor: "#DD6B55",
        cancelButtonText: "取消",
        showLoaderOnConfirm: true,
      }, function (isConfirm) {
        if (isConfirm) {
          that.editService.changeFileName(item.nAttachNo, newFileName).subscribe(data => {
            if (data) {
              window['swal']("成功", "附件名修改成功!", "success");
              that.loadFileTree();
            }
          })
        }
      })
    } else {
      window['swal']("注意", "附件名不能为空", "warning")
    }
  }
  // 取消编辑附件名
  cancelEditFileName(item, type) {
    let index;
    switch (type) {
      case "cpfaYDD":
        index = _.indexOf(this.cpfaYDDDataList, item);
        this.cpfaYDDDataList[index].editStatus = "0";
        break;
      case "flwjYDD":
        index = _.indexOf(this.flwjYDDDataList, item);
        this.flwjYDDDataList[index].editStatus = "0";
        break;
      case "baYDD":
        index = _.indexOf(this.baYDDDataList, item);
        this.baYDDDataList[index].editStatus = "0";
        break
      case "bcxyYDD":
        index = _.indexOf(this.bcxyYDDDataList, item);
        this.bcxyYDDDataList[index].editStatus = "0";
        break;
      case "zhxxYDD":
        index = _.indexOf(this.zhxxYDDDataList, item);
        this.zhxxYDDDataList[index].editStatus = "0";
        break;
      case "tzxxYDD":
        index = _.indexOf(this.tzxxYDDDataList, item);
        this.tzxxYDDDataList[index].editStatus = "0";
        break;
      case "qsxxYDD":
        index = _.indexOf(this.qsxxYDDDataList, item);
        this.qsxxYDDDataList[index].editStatus = "0";
        break;
      case "qtYDD":
        index = _.indexOf(this.qtYDDDataList, item);
        this.qtYDDDataList[index].editStatus = "0";
        break;
    }
  }
  // 切换tab清空附件类型
  clearFileType() {
    this.activeFileType = "";
  }
  // 激活文件tab
  activeFileTab() {
    let that = this;
    window['$']('#cpfaYDD_List').removeClass('active');
    window['$']('#tab_9').removeClass('active');
    window['$']("#cpfaYDD_Content").attr('aria-expanded', "false");
    window['$']('#flwjYDD_List').removeClass('active');
    window['$']('#tab_10').removeClass('active');
    window['$']("#flwjYDD_Content").attr('aria-expanded', "false");
    window['$']('#baYDD_List').removeClass('active');
    window['$']('#tab_11').removeClass('active');
    window['$']("#baYDD_Content").attr('aria-expanded', "false");
    window['$']('#zhxxYDD_List').removeClass('active');
    window['$']('#tab_12').removeClass('active');
    window['$']("#zhxxYDD_Content").attr('aria-expanded', "false");
    window['$']('#bcxyYDD_List').removeClass('active');
    window['$']('#tab_13').removeClass('active');
    window['$']("#bcxyYDD_Content").attr('aria-expanded', "false");
    window['$']('#tzxxYDD_List').removeClass('active');
    window['$']('#tab_14').removeClass('active');
    window['$']("#tzxxYDD_Content").attr('aria-expanded', "false");
    window['$']('#qsxxYDD_List').removeClass('active');
    window['$']('#tab_15').removeClass('active');
    window['$']("#qsxxYDD_Content").attr('aria-expanded', "false");
    window['$']('#qtYDD_List').removeClass('active');
    window['$']('#tab_16').removeClass('active');
    window['$']("#qtYDD_Content").attr('aria-expanded', "false");
    if (this.activeFileType == "") {
      this.activeFileType = this.activeFileList[0];
    }
    switch (this.activeFileType) {
      case "cpfaYDD":
        window['$']('#cpfaYDD_List').addClass('active');
        window['$']('#tab_9').addClass('active');
        window['$']("#cpfaYDD_Content").attr('aria-expanded', "true");
        break;
      case "flwjYDD":
        window['$']('#flwjYDD_List').addClass('active');
        window['$']('#tab_10').addClass('active');
        window['$']("#flwjYDD_Content").attr('aria-expanded', "true");
        break;
      case "baYDD":
        window['$']('#baYDD_List').addClass('active');
        window['$']('#tab_11').addClass('active');
        window['$']("#baYDD_Content").attr('aria-expanded', "true");
        break;
      case "bcxyYDD":
        window['$']('#bcxyYDD_List').addClass('active');
        window['$']('#tab_12').addClass('active');
        window['$']("#bcxyYDD_Content").attr('aria-expanded', "true");
        break;
      case "zhxxYDD":
        window['$']('#zhxxYDD_List').addClass('active');
        window['$']('#tab_13').addClass('active');
        window['$']("#zhxxYDD_Content").attr('aria-expanded', "true");
        break;
      case "tzxxYDD":
        window['$']('#tzxxYDD_List').addClass('active');
        window['$']('#tab_14').addClass('active');
        window['$']("#tzxxYDD_Content").attr('aria-expanded', "true");
        break;
      case "qsxxYDD":
        window['$']('#qsxxYDD_List').addClass('active');
        window['$']('#tab_15').addClass('active');
        window['$']("#qsxxYDD_Content").attr('aria-expanded', "true");
        break;
      case "qtYDD":
        window['$']('#qtYDD_List').addClass('active');
        window['$']('#tab_16').addClass('active');
        window['$']("#qtYDD_Content").attr('aria-expanded', "true");
        break;
    }
  }
  // 公募查询单个产品基础信息
  pcGetSingleProduct() {
    let that = this;
    this.editService.pcGetSingleProduct(this.nFundNo).subscribe(data => {
      if (data) {
        that.baseInfoPost = data;
        console.info(that.otmAddOrEditBody);
        // 销售渠道转换
        that.salesSelectList = _.concat([], data.sSalesChannels);
        that.otmIsAisle();
        that.IsContractPeriod();
        // 数据加载完成后，再次加载下拉框，消除样式问题
        setTimeout(function () {
          // 多选下拉框
          window['$'](".select2").select2();
        }, 1);
      }
    })
  }
  //一对一查询单个产品基础信息
  otoGetSingleProduct() {
    let that = this;
    this.editService.otoGetSingleProduct(this.nFundNo).subscribe(data => {
      if (data) {
        that.otoAddOrEditBody = data;
        // 销售渠道转换
        that.salesSelectList = _.concat([], data.sSalesChannels);
        that.otmIsAisle();
        that.IsContractPeriod();
        // 数据加载完成后，再次加载下拉框，消除样式问题
        setTimeout(function () {
          // 多选下拉框
          window['$'](".select2").select2();
        }, 1);
      }
    })
  }
  //一对多查询单个产品基础信息
  otmGetSingleProduct() {
    let that = this;
    this.editService.otmGetSingleProduct(this.nFundNo).subscribe(data => {
      if (data) {
        that.otmAddOrEditBody = data;
        // 销售渠道转换
        that.salesSelectList = _.concat([], data.sSalesChannels);
        that.otmIsAisle();
        that.IsContractPeriod();
        // 数据加载完成后，再次加载下拉框，消除样式问题
        setTimeout(function () {
          // 多选下拉框
          window['$'](".select2").select2();
        }, 1);
      }
    })
  }
  // 公募编辑产品基础信息
  editBasicInfo() {
    let that = this;
    // this.baseInfoPost.sPmAccount = this.ctrlManagerId();
    // this.baseInfoPost.sPmName = this.ctrlManagerName();
    this.baseInfoPost['nFundNo'] = this.nFundNo;
      //判断成立日期不能比发行日期早
      // if (this.beforeTime()) {
        window["swal"]({
          title: "提示",
          text: "是否确定保存基础信息?",
          type: "warning",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          showCancelButton: true,
          closeOnConfirm: false,
          closeOnCancel: true,
          showLoaderOnConfirm: true
        }, function (isConfirm) {
          if (isConfirm) {
            that.editService.editBasic(that.baseInfoPost).subscribe(data => {
              if (data) {
                window['swal']("提示", "基础信息保存成功", "success");
              }
            })
          }
        })
      // } else {
      //   window['swal']("提示", "发行日期不能比成立日期早", "warning");
      // }
     }

     // 一对多编辑产品基础信息
  otmAddOrEditBasicInfo(){
    let that =this;
    let parameter = that.otmAddOrEditBody;
    delete parameter.sTrustee;
    delete parameter.sFundCategoryZh;
    delete parameter.sSalesChannels;
    window["swal"]({
      title: "提示",
      text: "是否确定保存基础信息?",
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      showCancelButton: true,
      closeOnConfirm: false,
      closeOnCancel: true,
      showLoaderOnConfirm: true
    }, function (isConfirm) {
      if (isConfirm) {
        that.editService.otmEditProduct(parameter).subscribe(data => {
          if (data) {
            window['swal']("成功", "修改成功!", "success");
          }
        })
      }
    })
  }
  // 一对多编辑产品基础信息
  otoAddOrEditBasicInfo(){
    let that =this;
    let parameter = that.otoAddOrEditBody;
    delete parameter.sTrustee;
    delete parameter.sFundCategoryZh;
    delete parameter.sSalesChannels;
    window["swal"]({
      title: "提示",
      text: "是否确定保存基础信息?",
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      showCancelButton: true,
      closeOnConfirm: false,
      closeOnCancel: true,
      showLoaderOnConfirm: true
    }, function (isConfirm) {
      if (isConfirm) {
        that.editService.otoEditProduct(parameter).subscribe(data => {
          if (data) {
            window['swal']("成功", "修改成功!", "success");
          }
        })
      }
    })
  }

    // 查询投资经理信息
  otmGetManager(pageNum?, pageSize?) {
    let that = this;
    this.otmManagerBody.nFundNo = this.nFundNo;
    this.otmManagerBody.pageIndex = pageNum ? pageNum : this.otmManagerListPageInfo.currentPageNum;
    this.otmManagerBody.pageSize = pageSize ? pageSize : this.otmManagerListPageInfo.pageSize;
    this.editService.otmGetManager(this.otmManagerBody).subscribe(data => {
      if (data) {
        that.otmManagerList = data.list;
        that.otmManagerListPageInfo.currentPageNum = data.pageNum;
        that.otmManagerListPageInfo.totalPages = data.pages;
        that.otmManagerListPageInfo.total = data.total;
        that.otmManagerListPageInfo.startRow = data.startRow;
        that.otmManagerListPageInfo.endRow = data.endRow;
      }
    })
  }
  // 投资经理切换页
  otmManagerPagesizeChange(pageSize: number) {
    if (pageSize !== this.otmManagerListPageInfo.pageSize) {
      this.otmManagerListPageInfo.pageSize = pageSize;
      this.otmGetManager();
    }
  }
  // 投资经理分页
  otmManagerPageNavigation(currentPageNum: number) {
    this.otmManagerListPageInfo.currentPageNum = currentPageNum;
    this.otmGetManager(this.otmManagerListPageInfo.currentPageNum, this.otmManagerListPageInfo.pageSize);
  }
  // 一对多新增或编辑产品
  // otmAddOrEditBasicInfo(type) {
  //   let that = this;
  //   this.otmAddOrEditBody.sFundType = "2";
  //   this.otmAddOrEditBody.sSalesChannel = this.ctrlSalesId();
  //   if (this.requireAdd()) {
  //     if (this.beforeRunTime()) {
  //       if (this.beforeIssueTime()) {
  //         window["swal"]({
  //           title: "提示",
  //           text: "是否确定保存基础信息?",
  //           type: "warning",
  //           confirmButtonText: "确认",
  //           cancelButtonText: "取消",
  //           showCancelButton: true,
  //           closeOnConfirm: false,
  //           closeOnCancel: true,
  //           showLoaderOnConfirm: true
  //         },
  //           function (isConfirm) {
  //             if (isConfirm) {
  //               if (type == 'add') {
  //                 let publicUrl: any = { "url": "/pages/onetomany/new/detail/add" };
  //                 that.otmAddOrEditBody.sStatusRunning = "1";
  //                 that.editService.otmAddProduct(that.otmAddOrEditBody).subscribe(data => {
  //                   if (data) {
  //                     window['swal']("成功", "新增成功!", "success");
  //                     that.otmAddOrEditBody = {};
  //                     that.dataService.public_url.emit(publicUrl);
  //                     that.router.navigate(['/pages/onetomanyList/wcl']);
  //                   }
  //                 })
  //               }
  //               if (type == 'edit') {
  //                 let parameter = that.otmAddOrEditBody;
  //                 delete parameter.sTrustee;
  //                 delete parameter.sFundCategoryZh;
  //                 delete parameter.sSalesChannels;
  //                 that.editService.otmEditProduct(parameter).subscribe(data => {
  //                   if (data) {
  //                     window['swal']("成功", "修改成功!", "success");
  //                   }
  //                 })
  //               }
  //             }
  //           })
  //       } else {
  //         window['swal']("提示", "发行结束日不能比发行起始日早", "warning");
  //       }
  //     } else {
  //       window['swal']("提示", "到期日不能比起始运作日期早", "warning");
  //     }
  //   }
  // }
  // 判断合同期限
  IsContractPeriod() {
    if (this.otmAddOrEditBody.sIsContractPeriod == "1") {
      this.otmAddOrEditBody.nContractPeriod = "";
      window['$']('#nContractPeriod').attr("disabled", "disabled");
      window['$']('#nContractPeriod').css("background", "#eee");
    }
    if (this.otmAddOrEditBody.sIsContractPeriod == "0") {
      window['$']('#nContractPeriod').removeAttr("disabled");
      window['$']('#nContractPeriod').css("background", "#ffffff");
    }
  }
  // 创设-(发行起始日/发行结束日)-校验
  beforeIssueTime() {
    if (this.otmAddOrEditBody.dIssue !== "" && this.otmAddOrEditBody.dIssue !== null && this.otmAddOrEditBody.dIssueEnd !== "" && this.otmAddOrEditBody.dIssueEnd !== null) {
      if (this.otmAddOrEditBody.dIssue == this.otmAddOrEditBody.dIssueEnd) {
        return true;
      } else {
        if (moment(this.otmAddOrEditBody.dIssue).isBefore(this.otmAddOrEditBody.dIssueEnd)) {
          return true;
        } else {
          return false;
        }
      }
    } else {
      return true;
    }
  }
  // 创设-(起始运作日期/到期日)-校验
  beforeRunTime() {
    if (this.otmAddOrEditBody.dBegin !== "" && this.otmAddOrEditBody.dBegin !== null && this.otmAddOrEditBody.dEnd !== "" && this.otmAddOrEditBody.dEnd !== null) {
      if (this.otmAddOrEditBody.dBegin == this.otmAddOrEditBody.dEnd) {
        return true;
      } else {
        if (moment(this.otmAddOrEditBody.dBegin).isBefore(this.otmAddOrEditBody.dEnd)) {
          return true;
        } else {
          return false;
        }
      }
    } else {
      return true;
    }
  }
  // 是否通道类专户控制
  otmIsAisle() {
    if (this.otmAddOrEditBody.sIsAisle == '1') {
      window['$']('#sCapitalpro').removeAttr("disabled");
      window['$']('#sCapitalproType').removeAttr("disabled");
    }
    if (this.otmAddOrEditBody.sIsAisle == '0') {
      this.otmAddOrEditBody.sCapitalpro = "";
      this.otmAddOrEditBody.sCapitalproType = "";
      window['$']('#sCapitalpro').attr("disabled", "disabled");
      window['$']('#sCapitalproType').attr("disabled", "disabled");
    }
  }
  // 已成立产品信息修改,修改信息后去到审核面板(不直接修改信息)
  otmCheckProductEdit() {
    let that = this;
    // 产品业务类型,修改(1)、续约(2)、终止(3)、开始运作(4)
    let businessType = "1";
    this.otmAddOrEditBody.sSalesChannel = this.ctrlSalesId();
    if (this.requireAdd()) {
      if (this.beforeRunTime()) {
        if (this.beforeIssueTime()) {
          window["swal"]({
            title: "提示",
            text: "是否确定保存基础信息?",
            type: "warning",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            showCancelButton: true,
            closeOnConfirm: false,
            closeOnCancel: true,
            showLoaderOnConfirm: true
          },
            function (isConfirm) {
              if (isConfirm) {
                let parameter = that.otmAddOrEditBody;
                delete parameter.sTrustee;
                delete parameter.sFundCategoryZh;
                delete parameter.sSalesChannels;
                that.editService.operationType(that.otmAddOrEditBody, businessType).subscribe(data => {
                  if (data) {
                    window['swal']("成功", "请等待产品审核!", "success");
                  }
                })
              }
            })
        } else {
          window['swal']("提示", "发行结束日不能比发行起始日早", "warning");
        }
      } else {
        window['swal']("提示", "到期日不能比起始运作日期早", "warning");
      }
    }
  }
  // 新增、编辑必填校验
  requireAdd() {
    let that = this;
    let requiredAddTip = [];
    let sFullName = _.trim(this.otmAddOrEditBody.sFullName);
    let sFundName = _.trim(this.otmAddOrEditBody.sFundName);
    if (sFullName == "" || sFullName == null) {
      requiredAddTip.push("产品名称");
    }
    if (sFundName == "" || sFundName == null) {
      requiredAddTip.push("产品简称");
    }
    if (requiredAddTip.length > 0) {
      let requiredAddTips = requiredAddTip.join("、");
      window['swal']("提示", "请填写:" + requiredAddTips, "warning");
      return false;
    } else {
      return true;
    }
  }

  计算合同到期日
  countMonth() {
    if (this.otmAddOrEditBody.dBegin && this.otmAddOrEditBody.nContractPeriod) {
      this.otmAddOrEditBody.dEnd = moment(this.otmAddOrEditBody.dBegin).add(this.otmAddOrEditBody.nContractPeriod, 'months').format('YYYY-MM-DD')
    } else {
      this.otmAddOrEditBody.dEnd = '';
    }
  }

  // 获取销售渠道下拉框选项ID
  ctrlSalesId() {
    let salesIdList: any;
    let salesChecked = [];
    let selected = window['$']('.fields-select').val();
    _.forEach(selected, item => {
      let index1 = item.indexOf("'");
      let index2 = item.lastIndexOf("'");
      let sales = item.substring(index1 + 1, index2);
      salesChecked.push(sales);
    })
    salesIdList = salesChecked.join(",");
    return salesIdList;
  }
  // 多选下拉框基金经理Name
  // ctrlSalesName() {
  //   let that = this;
  //   let salesNameList: any;
  //   let salesChecked = [];
  //   let salesId = this.ctrlSalesId().split(",");
  //   _.forEach(salesId, item => {
  //     _.forEach(that.saleslList, it => {
  //       if (item == it.sItemKey) {
  //         salesChecked.push(it.sItemValue);
  //       }
  //     })
  //   })
  //   salesNameList = salesChecked.join(",");
  //   return salesNameList;
  // }
  //  截取文件名称类型
  Intercept(item) {
    let str = item;
    if (str) {
      let arr = str.split('.');
      let newarr = arr[arr.length - 1];
      return newarr;
    }
  }
  //控制未成立新增和编辑3个字段不可编辑
  ctrlDisabled(){
     if(this.index=='wcl' || this.index=='new'){
       window['$']('#dBegin').attr("disabled", "disabled");
       window['$']('#dBegin').css("background", "#eeeeee");
       window['$']('#dEnd').attr("disabled", "disabled");
       window['$']('#dEnd').css("background", "#eeeeee");
       window['$']('#sFundCode').attr("disabled", "disabled");
       window['$']('#sFundCode').css("background", "#eeeeee");
      }else{
       window['$']('#dBegin').removeAttr("disabled");
       window['$']('#dEnd').removeAttr("disabled");
       window['$']('#sFundCode').removeAttr("disabled");
      }
   }
}
